package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理物流信息（商品寄送的地址）
 */
@Slf4j
@Component
public class LogisticalHandler extends AbstractTransHandler {
    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        //再插入订单地址表order-shipping
        OrderShipping target = getOrderShippingByCreateOrder(createOrderContext);
        int affectRows = orderShippingMapper.insertSelective(target);
        if (affectRows < 1) {
            throw new BizException(OrderRetCode.SHIPPING_DB_SAVED_FAILED.getCode(),
                    OrderRetCode.SHIPPING_DB_SAVED_FAILED.getMessage());
        }
        return true;
    }

    private OrderShipping getOrderShippingByCreateOrder(CreateOrderContext createOrderContext) {
        OrderShipping orderShipping = new OrderShipping();
        orderShipping.setOrderId(createOrderContext.getOrderId());
        orderShipping.setReceiverName(createOrderContext.getUserName());
        orderShipping.setReceiverPhone(createOrderContext.getTel());
        orderShipping.setReceiverMobile(createOrderContext.getTel());
        //这里对地址做一个处理
        String streetName = createOrderContext.getStreetName();
        String[] split = streetName.split("-");
        String receiverState = split[0];
        String receiverCity = split[1];
        String receiverDistrict = split[2];
        //这里是前端一些bug这么存才能全部回显
        String receiverAddress = streetName;
        orderShipping.setReceiverState(receiverState);
        orderShipping.setReceiverCity(receiverCity);
        orderShipping.setReceiverDistrict(receiverDistrict);
        orderShipping.setReceiverAddress(receiverAddress);
        orderShipping.setCreated(new Date());
        orderShipping.setUpdated(new Date());
        return orderShipping;
    }
}
